﻿using ARS.Common;
using ARS.Common.Helper;
using ARS.Common.Service;
using ARS.Common.Service.Model;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;


namespace ARS.Service
{
    class Program
    {
      
        static void Main(string[] args)
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            var config = new ConfigurationBuilder().AddJsonFile(path: "appsettings.json", optional: true, reloadOnChange: true).Build();
            string arsName = config["AppSetting:ArsName"];
            string arsDbStr = config["AppSetting:ArsDbStr"];
            string execPath = config["AppSetting:ExecPath"];

            string webHook = config["AppSetting:WebHook"];
            string linkUrl = config["AppSetting:linkUrl"];
            string siteUrl = config["AppSetting:siteUrl"];
            bool isOpenHook = Convert.ToBoolean(config["AppSetting:isOpenHook"]);



            Console.Title = arsName;
            Log.WriteLine(arsName);
            Log.WriteLine($"邮件发送传入参数:\r\n {string.Join(',', args)}\r\n");
            BuilderServices.Init(arsDbStr);

            if (args.Length > 0)
            {
                CallModel dataModel = new CallModel();
                var result = args.Select(x =>
                  {
                      var arrdata = x.Split("=");
                      if (arrdata.Length >= 2)
                      {
                          if (arrdata[0].ToLower() == "etid")
                          {
                              dataModel.etId = int.Parse(arrdata[1]);
                              return new KeyValuePair<string, string>("", "");
                          }
                          else
                              return new KeyValuePair<string, string>(arrdata[0], arrdata[1]);
                      }
                      else
                          return new KeyValuePair<string, string>("", "");
                  }).Where(x => !string.IsNullOrEmpty(x.Key)).ToList();


                dataModel.eParams = result;
                if (dataModel == null || dataModel.etId < 1)
                    Log.WriteLine("传递的参数错误，无法执行邮件发送程序");

                var _logPath = Path.Combine(execPath, "logs", dataModel.etId.ToString());
                if (!Directory.Exists(_logPath))
                    Directory.CreateDirectory(_logPath);
                BuilderServices.Run(dataModel.etId, dataModel.eParams, execPath, Tuple.Create<bool, string, string>(isOpenHook, webHook, siteUrl), linkUrl);
                Log.WriteLine("程序执行完成", ConsoleColor.Red);
            }
            else
            {
                Log.WriteLine("没有参数，无法执行邮件发送程序");
            }

        }
    }
}
